package com.yonyou.cloud.member.adapters.repository.orm.dao.impl;

import com.yonyou.cloud.member.adapters.repository.orm.dao.CouponDao;
import com.yonyou.cloud.member.adapters.repository.orm.dao.MemberDao;
import com.yonyou.cloud.member.domainmodel.entities.coupon.Coupon;
import com.yonyou.cloud.member.domainmodel.vo.CouponId;
import com.yonyou.cloud.member.domainmodel.entities.coupon.CouponStatusEnum;
import com.yonyou.cloud.member.domainmodel.entities.coupon.DiscountCoupon;
import com.yonyou.cloud.member.domainmodel.vo.MemberId;
import com.yonyou.cloud.member.libs.key.KeyGenerator;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class MockCouponDaoImpl implements CouponDao, InitializingBean {
    @Autowired
    KeyGenerator keyGenerator;

    List<Coupon> coupons;

    @Autowired
    MemberDao memberDao;


    @Override
    public void afterPropertiesSet() throws Exception {
        coupons = new ArrayList<>();
        coupons.add(new DiscountCoupon(keyGenerator.generate(CouponId.class), memberDao.first(), "三折优惠券").setDiscount(new BigDecimal(0.3)).setThresholdMoney(new BigDecimal(300)).setEffectiveDate(LocalDate.now().atStartOfDay(), 10));
        coupons.add(new DiscountCoupon(keyGenerator.generate(CouponId.class), memberDao.first(), "五折优惠券").setDiscount(new BigDecimal(0.5)).setThresholdMoney(new BigDecimal(200)).setEffectiveDate(LocalDate.now().atStartOfDay(), 10));
        coupons.add(new DiscountCoupon(keyGenerator.generate(CouponId.class), memberDao.first(), "七折优惠券").setDiscount(new BigDecimal(0.7)).setThresholdMoney(new BigDecimal(100)).setEffectiveDate(LocalDate.now().atStartOfDay(), 10));
    }

    @Override
    public Coupon find(CouponId couponId) {
        Coupon coupon = coupons.stream().filter(c -> c.getId().equals(couponId)).findAny().orElse(null);
        return coupon;
    }

    @Override
    public List<Coupon> listByMember(MemberId memberId) {
        return coupons.stream().filter(c -> c.isAvailable() && c.getMemberId().equals(memberId)).collect(Collectors.toList());
    }

    @Override
    public boolean updateStatus(CouponId couponId, CouponStatusEnum status) {
        Coupon coupon = coupons.stream().filter(c -> c.getId().equals(couponId)).findAny().orElse(null);
        if (coupon != null) {
            coupon.setStatus(status);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean reset() {
        for (Coupon coupon : coupons) {
            coupon.setEffectiveDate(LocalDate.now().atStartOfDay(), 10).setStatus(CouponStatusEnum.NEW);
        }
        return true;
    }

}